package com.ins1st.config.web;

import com.ins1st.plugins.MybatisInterceptor;
import com.ins1st.util.ShiroUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.session.InvalidSessionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

/**
 * @program: ins1st-cloud
 * @description:
 * @author: coderSun
 * @create: 2019-11-22 13:44
 **/
@Configuration
public class FeignRequestInterceptor implements RequestInterceptor {

    private static final Logger log = LoggerFactory.getLogger(MybatisInterceptor.class);

    @Override
    public void apply(RequestTemplate requestTemplate) {
        try {
            if (ShiroUtil.getSubject().getSession().getAttribute("tenant_id") != null) {
                String tenantId = (String) ShiroUtil.getSubject().getSession().getAttribute("tenant_id");
                log.debug("当前租户id: {}",tenantId);
                requestTemplate.header("tenant_id", !StringUtils.equals("1197864238920564737", tenantId) ? tenantId : null);
            } else if (ShiroUtil.getUser() != null && StringUtils.isNotBlank(ShiroUtil.getUser().getTenantId())) {
                log.debug("当前租户id: {}",ShiroUtil.getUser().getTenantId());
                requestTemplate.header("tenant_id", !StringUtils.equals("1197864238920564737", ShiroUtil.getUser().getTenantId()) ? ShiroUtil.getUser().getTenantId() : null);
            }
        } catch (InvalidSessionException e) {

        }

    }
}
